import React, { Component, ChangeEvent } from 'react';

import styles from './index.css';
import { List, Layout, Icon, Button, Tooltip, Modal, Form, Input, message } from 'antd';
import Model, { todoState } from '../model/model';
import TodoEntity, { firstEntity, createEmptyEntity } from '../model/entity/todo_entity';
import { observable } from 'mobx';
import { observer } from 'mobx-react';

const Header = Layout.Header;

enum editType {
  edit,
  add,
}

const initState = {
  showModal: false,
  modalEntity: firstEntity,
  editType: editType.add,
};

type State = Readonly<typeof initState>;

var modal = observable({
  showModal: false,
  text: '',
  modalKey: 0,
});

@observer
export default class TodoIndex extends Component<{}, State> {
  state = initState;
  onChangeInput(event: ChangeEvent<HTMLInputElement>) {
    modal.text = event.target.value;
  }

  render() {
    return (
      <Layout>
        <Header style={{ backgroundColor: '#4F94CD' }}>
          <span style={{ color: 'white' }}>todo</span>
          <Tooltip title="添加todo">
            <Button icon="plus-circle" onClick={this.showOrhide} />
          </Tooltip>
        </Header>
        <Layout.Content>
          <List
            dataSource={todoState.todolist}
            renderItem={(item: TodoEntity) => (
              <List.Item>
                <List.Item.Meta title={item.title} />
              </List.Item>
            )}
            locale={{ emptyText: '还没数据' }}
          />
          <Modal
            key={modal.modalKey}
            visible={modal.showModal}
            onCancel={() => {
              modal.showModal = false;
            }}
            onOk={() => {
              addTodoEntity();
              modal.modalKey = Math.random();
              console.log(`key = ${modal.modalKey}`);
            }}
            okText="确定"
            cancelText="取消"
          >
            <div style={{ paddingTop: 15 }}>
              <Form>
                <Input
                  placeholder="输入todo的内容"
                  onChange={this.onChangeInput}
                  key={modal.modalKey}
                />
              </Form>
            </div>
          </Modal>
        </Layout.Content>
      </Layout>
    );
  }
  showOrhide() {
    modal.showModal = true;
  }
}

function addTodoEntity() {
  if (!modal.text) {
    message.error('必须输入内容');
    return;
  }
  var entity = createEmptyEntity();
  entity.title = modal.text;
  todoState.todolist.push(entity);
  modal.showModal = false;
}
